//
//  ZMTabBar.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/22.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit

//代理协议
protocol ZMTabBarDelegate : NSObjectProtocol{
    
    //定义代理方法
    func addButtonClick()
    
    
}



class ZMTabBar: UITabBar {

    //定义代理属性
    
    weak var buttonDelegate : ZMTabBarDelegate?
    
    //定义闭包,按钮单击回调
    var btnclickClosure: (()->())?
    
    
   //懒加载button
    lazy var button: UIButton = {
       
        let btn = UIButton(type: UIButtonType.custom)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add"), for: UIControlState.normal)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .highlighted)
        
        btn.sizeToFit()
        return btn
    }()
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI(){
        
        self.addSubview(button)
        
        //  设置背景图片，解决push阴影问题
        backgroundImage = UIImage(named: "tabbar_background")
        //添加单击事件
        button.addTarget(self, action: #selector(buttonclick), for: .touchUpInside)
        
    }
    
    //按钮单击事件
   @objc private func buttonclick(){
       // 执行闭包回调函数
        btnclickClosure?()
       // 执行代理回调函数
       buttonDelegate?.addButtonClick()
    }
    
    
    
    //重新布局
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let w = UIScreen.main.bounds.width / CGFloat(subviews.count-1)
        
        let h = self.bounds.height
        
        var index = 0
        
        for btn in subviews {
            
            if btn.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                btn.frame = CGRect.init(x:CGFloat(index)*w, y: 0, width: w, height: h)
                
                index += (index == ((subviews.count-1)/2-1)) ? 2 : 1
                
                
            }
            
            
        }
        //设置按钮
        button.center = CGPoint.init(x: self.center.x, y: bounds.height/2)
        button.bounds.size = CGSize.init(width: w, height: h)
        
        
        
    }
    
    
    

}
